const config    = require('../config/config');
const request   = require('request');
const setCookie = require('set-cookie-parser');
const crypto    = require('crypto');
class elves_login{

    constructor(username,password) {

        var epassword = crypto.createHash('md5').update(password).digest("hex");
        var slat = crypto.createHash('md5').update((username + epassword).toString()).digest("hex");

        this.formData = {
            password: epassword,
            email: username,
            password_otn: password,
            salt:slat
        }
    }

    async do(){
        return new Promise((resolve, reject) => {
            let options = {
                url: 'https://www.sellersprite.com/w/user/signin',
                method: 'POST',
                // proxy: `http://${config.PROXY.HOST}:${config.PROXY.PORT}`,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                form: this.formData
            };
            request(options,async (err,response,body) => {
                console.log(`body:${JSON.stringify(body)}`)
                if(err){
                    console.log(`<<<<<<<>>>>>>>>> Elves login failed. Error:${err}`);
                    reject(err.message)
                }else{
                    let cookie = '';
                    let cookies = setCookie.parse(response,{decodeValues:true});
                    for (let ck of cookies){
                        cookie += ck.name;
                        cookie += '=';
                        cookie += ck.value;
                        cookie += ';'
                    }
                    console.log(`Elves login success. Cookie:${cookie}`);
                    resolve(cookie);
                }
            })
        })
    }
}

module.exports = elves_login;
